import Foundation
import Alamofire

import Hyphenate
class CUHTTP: NSObject{
    
    //TODO: remove app transport security arbitary constant from info.plist file once we get API's
    var request : URLRequest?
    var session : URLSession?
    
    static func instance() ->  CUHTTP{
        
        return CUHTTP()
    }
    struct URL {
//        static var ROOT = "https://api.curtainups.com/"
        
       static var ROOT = "http://128.199.144.186/"
    }
    func makeUrl (word:String)->String {
        return URL.ROOT + word
    }
    
//    func makePost(url: String,params: Dictionary<String, Any>?, success:@escaping (HTTPURLResponse?) -> Void, failure: @escaping (HTTPURLResponse?)-> Void) {
//        Alamofire.request(makeUrl(word:url), method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { response in
//            let statusCode = response.response?.statusCode;
//            if(statusCode == 200){
//                success(response.response)
//            }else{
//                failure(response.response)
//            }
//        }
//    }

    func makePostData(url: String, parameters: [String: Any],success:@escaping (DataResponse<String>?) -> Void, failure: @escaping (String?)-> Void) {

        let pre = Locale.current.languageCode
        let item: [String: Any] = [
            "lang": pre ?? "en"
        ]
        let para = item.merging(parameters) { (_, new) -> Any in
            new
        }
        
        let authToken:String = UserDefaults.standard.string(forKey: "authToken") ?? ""
        let username:String = EMClient.shared()?.isLoggedIn ?? false ? EMClient.shared().currentUsername : ""
        let headers: HTTPHeaders = [
            "Username": username,
            "Authorization": authToken
        ]
        
        print("post request:" + makeUrl(word:url))

        Alamofire.request( makeUrl(word:url), method: .post, parameters: para, encoding: JSONEncoding.default, headers:headers)
            .responseString { response in
                let statusCode = response.response?.statusCode;
                if(statusCode == 200){
                    success(response)
                }else{
                    do {
                    let data = try response.result.value?.data(using: String.Encoding.utf8)! as! NSData
                    let json = try JSONSerialization.jsonObject(with: data as Data,
                                                                 options:.allowFragments) as! [String: Any]
                     let loopE = try json as! [String: Any]
                        if let tmpStr0 = loopE["description"] {
                        if let tmpStr1 = (tmpStr0 as? String) {
                            failure(tmpStr1)
                        }
                    }
                    }catch {
                    
                        failure("request failed".localized())
                    }
                }
        }
    }
    
    func makeGetData(url: String, success:@escaping (DataResponse<String>?) -> Void, failure: @escaping (String?)-> Void) {
        
        let authToken:String = UserDefaults.standard.string(forKey: "authToken") ?? ""
        let username:String = EMClient.shared()?.isLoggedIn ?? false ? EMClient.shared().currentUsername : ""
        let headers: HTTPHeaders = [
            "Username": username,
            "Authorization": authToken
        ]
        
        print("get request:" + makeUrl(word:url))
        
        Alamofire.request( makeUrl(word:url), method: .get, parameters: nil, encoding: JSONEncoding.default,headers:headers)
            .responseString { response in
                let statusCode = response.response?.statusCode;
                if(statusCode == 200){
                    success(response)
            }
                else if(statusCode == 500 || statusCode == nil){
                    failure("request failed".localized())
                }else {
                    do {
                        let data = try response.result.value?.data(using: String.Encoding.utf8)! as! NSData
                        let json = try JSONSerialization.jsonObject(with: data as Data,
                                                                    options:.allowFragments) as! [String: Any]
                        let loopE = try json as! [String: Any]
                        if let tmpStr0 = loopE["description"] {
                            if let tmpStr1 = (tmpStr0 as? String) {
                                failure(tmpStr1)
                            }
                        }
                    }catch {
                        
                        failure("request failed".localized())
                    }
                }
        }
    }
}
